<?php
namespace Common\Model;
use Common\Model\CommonModel;
use Think\Exception;

class StoreModel extends CommonModel {

    //店铺性质  1线下店铺  2个人推广
    const STORE_SHOP = 'shops';
    const STORE_PERSONAL = 'personal';
    //映射关系
    public static $getStoreTypeValue = array(
        self::STORE_SHOP   => '线下店铺',
        self::STORE_PERSONAL => '个人推广',
    );

    public function getStoreCount($cond){
        $res = M('store')
            ->join('ecm_member on ecm_store.store_id = ecm_member.user_id')
            ->where($cond['condition'])
            ->field($cond['field'])
            ->order($cond['order'])
            ->select();
        return $res;
    }

    public function getStoreList($cond){
        $res = $this
            ->join('ecm_member on ecm_store.store_id = ecm_member.user_id')
            ->where($cond['condition'])
            ->page($cond['page'])
            ->field($cond['field'])
            ->order($cond['order'])
            ->select();
        $member_invite_code = D("member_invite_code");
        foreach($res as $k=>$v){
            $res[$k]['store_type_value'] = self::$getStoreTypeValue[$v['store_type']];
            $res[$k]['qr_code'] = C("WEB_PHOTO_SRC").'/'.$v['qr_code'];
            if($v['applet_code']){
                $res[$k]['applet_code'] = C("WEB_PHOTO_SRC").'/'.$v['applet_code'];
            }
            //判断是否为推广人
            if($v['is_promoters'] == 1){
                $res[$k]['promoters_code'] = $member_invite_code->where(array("user_id"=>$v['user_id']))->getField("invite_code");
            }else{
                $res[$k]['promoters_code'] = '无';
            }
        }
        return $res;
    }

    public function insertStoreInfo($data){
        if(!$data){
            return false;
        }
        $res = M('store')->add($data);
        return $res;
    }

    public function getStoreInfo($cond){
        if(!$cond){
            return false;
        }
        $res = $this->join('ecm_member on ecm_store.store_id = ecm_member.user_id')
            ->where($cond)
            ->find();
        //判断店铺是否为线下店铺  设置分佣比例
        $res['min_sub_value'] = $res['min_sub'];
        $res['max_sub_value'] = $res['max_sub'];
        if($res['store_type'] == 'personal'){
            $mallConfigModel = M("mall_config");
            $res['min_sub_value'] = $mallConfigModel->where(array('code'=>'promotion_proportion'))->getField('value');
        }
        return $res;
    }

    public function reviseStoreInfo($cond,$data){
        if(!$cond|| !$data){
            return false;
        }
        $res = M('store')->where($cond)->save($data);
        return $res;
    }
}